﻿using AutoMapper;
using B.S.BasicData.Api.Write.Application.Command.Account;
using B.S.BasicData.Domain.Entities;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interfaces;
using B.S.BasicData.Infrastructure.Utils;
using MD5Hash;
using MediatR;
using Yitter.IdGenerator;

namespace B.S.BasicData.Api.Write.Application.CommandHandler.Account
{
    /// <summary>
    /// 创建账号的中介者处理类
    /// </summary>
    public class CreateAccountHandler : IRequestHandler<CreateAccountCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<AccountModel> accountRepo;
        private readonly IMapper mapper;
        private readonly ILogger<CreateAccountHandler> logger;
        private readonly IBaseRepository<LogModel> logRepo;

        public CreateAccountHandler(IBaseRepository<AccountModel> accountRepo,
            IMapper mapper,
            ILogger<CreateAccountHandler> logger, IBaseRepository<LogModel> logRepo)
        {
            this.accountRepo = accountRepo;
            this.mapper = mapper;
            this.logger = logger;
            this.logRepo = logRepo;
        }
        /// <summary>
        /// 添加账号的中介者处理方法
        /// </summary>
        /// <param name="request">处理命令</param>
        /// <param name="cancellationToken">取消标记</param>
        /// <returns></returns>
        public Task<ApiResult<int>> Handle(CreateAccountCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();


            var model = mapper.Map<AccountModel>(request);
            model.Id = YitIdHelper.NextId();
            model.AccountPass = request.AccountPass.GetMD5();
            int r =  accountRepo.CreateAsync(model).Result;

            if (r > 0)
            {
                result.Msg = ApiEnums.CreateAccountOk.Descrption();
                result.Code = ApiEnums.CreateAccountOk;
                result.Data =r;

                logRepo.CreateAsync(new LogModel()
                {
                    Id = YitIdHelper.NextId(),
                    CreateName = model.AccountName,
                    LogContent = result.Msg,
                    CreatTime = DateTime.Now,

                });
            }
            else {
                result.Msg = ApiEnums.Fail.Descrption();
                result.Code = ApiEnums.Fail;
                result.Data = r;

                logRepo.CreateAsync(new LogModel()
                {
                    Id = YitIdHelper.NextId(),
                    CreateName = model.AccountName,
                    LogContent = result.Msg,
                    CreatTime = DateTime.Now,

                });
            }

            return Task.FromResult(result);
            
        }
    }
}
